package com.quectel.cms.controller.partybuilding;


import com.quectel.business.common.util.sys.SysCodeUtils;
import com.quectel.cms.controller.BaseController;
import com.quectel.cms.util.SessionHolder;
import com.quectel.constant.global.SystemConstants;
import com.quectel.util.aspect.log.annotation.Log;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.constant.sys.SysCodeKeyConstants;
import com.quectel.core.module.partybuilding.dto.PartyBuildingHelpRecordDto;
import com.quectel.core.module.partybuilding.dto.PartyBuildingHelpRecordPersonBindingDto;
import com.quectel.core.module.partybuilding.dto.PartyPersonDto;
import com.quectel.core.module.partybuilding.service.PartyBuildingHelpRecordService;
import com.quectel.core.module.partybuilding.service.PartyPersonService;
import com.quectel.util.common.*;
import com.quectel.util.kit.PageFetchKit;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author bob
 * @email bob.yu@quectel.com
 * @date 2023/05/24 11:38
 */
@RestController
@RequestMapping("partyBuildingHelpRecord")
@Tag(name = "PartyBuildingHelpRecordController", description = "党内帮扶管理相关api")
public class PartyBuildingHelpRecordController extends BaseController {

    @DubboReference
    private PartyBuildingHelpRecordService partyBuildingHelpRecordService;
    @DubboReference
    private PartyPersonService partyPersonService;


    /**
     * 导入党内帮扶记录
     */
    @PostMapping("importExcel")
    @RequirePermissions(values = "partyBuildingHelpRecord:importExcel")
    @Operation(summary = "导入党内帮扶记录")
    public Response<Object> importExcel(
            MultipartHttpServletRequest request
    ) {

        Iterator<String> fileNames = request.getFileNames();
        while (fileNames.hasNext()) {
            String next = fileNames.next();
            List<MultipartFile> files = request.getFiles(next);
            for (MultipartFile file : files) {
                int successPerson = 0;
                int total = 0;
                try {
                    //校验楼栋数据合法性
                    List<Map<Integer, String>> analysis = POIUtils.analysis(file.getInputStream(), 1, 0);

                    for (Map<Integer, String> map : analysis) {
                        total++;
                        try {
                            PartyBuildingHelpRecordDto partyBuildingHelpRecordDto = new PartyBuildingHelpRecordDto();

                            partyBuildingHelpRecordDto.setTenantId(SessionHolder.getSysUser().getTenantId());
                            partyBuildingHelpRecordDto.setPartyId(SessionHolder.getSysUser().getPartyId());
                            partyBuildingHelpRecordDto.setSubject(map.get(0));
                            partyBuildingHelpRecordDto.setType(SysCodeUtils.easyToGetValue(SysCodeKeyConstants.PARTY_BUILDING_HELP_TYPE, map.get(1), Byte.class));
                            partyBuildingHelpRecordDto.setDate(DateUtils.parse(map.get(2), DateUtils.FormatType.SIMPLE));

                            //参与人手机号,逗号隔开
                            String mobileStr = map.get(3);
                            List<PartyBuildingHelpRecordPersonBindingDto> bindingDtos = new ArrayList<>();
                            if (StringUtils.isNotBlank(mobileStr)) {
                                Set<String> splitArr = new HashSet<>(Arrays.asList(mobileStr.split(",")));
                                for (String mobile : splitArr) {
                                    PartyPersonDto partyPersonDto = partyPersonService.selectOne(partyBuildingHelpRecordDto.getTenantId(), mobile);
                                    if (partyPersonDto != null) {
                                        PartyBuildingHelpRecordPersonBindingDto buildingHelpRecordPersonBindingDto = new PartyBuildingHelpRecordPersonBindingDto();
                                        buildingHelpRecordPersonBindingDto.setPersonId(partyPersonDto.getId());
                                        bindingDtos.add(buildingHelpRecordPersonBindingDto);
                                    }

                                }
                            }
                            partyBuildingHelpRecordDto.setBindPerson(bindingDtos);
                            partyBuildingHelpRecordDto.setHelper(map.get(4));
                            partyBuildingHelpRecordDto.setMethod(map.get(5));
                            partyBuildingHelpRecordDto.setAmount(new BigDecimal(map.get(6)));
                            partyBuildingHelpRecordDto.setRemark(HtmlUtils.encode(map.get(7)));
                            partyBuildingHelpRecordDto.setCreator(SessionHolder.getSysUser().getUsername());
                            partyBuildingHelpRecordDto.setCreateTime(new Date());
                            partyBuildingHelpRecordService.saveOrUpdate(partyBuildingHelpRecordDto);
                            successPerson++;
                        } catch (Exception e) {
                            logger.error("解析某个人员信息出错", e);
                            continue;
                        }

                    }
                    return Response.customize(Response.getSUCCESS_CODE(), "导入党内帮扶记录数:" + successPerson + " 总条数:" + total);
                } catch (Exception e) {
                    logger.error("解析信息出错");
                }
            }
        }
        return Response.error("导入数据出错");
    }


    /**
     * 列表
     */
    @GetMapping("exportExcel")
    @RequirePermissions(values = "partyBuildingHelpRecord:exportExcel")
    @Operation(summary = "导出党内帮扶信息")
    @Log(express = "导出党内帮扶信息")
    public void exportExcel(@RequestParam Map<String, Object> params, HttpServletResponse hresp) {
        Request request = Request.configParamsNotPage(params);

        super.fillAuthorityData(params);

        List<PartyBuildingHelpRecordDto> result = PageFetchKit.fetchAll(req -> partyBuildingHelpRecordService.queryList(req), request.getParams());
        String[] headers = new String[]{"所属党组织", "帮扶主题", "帮扶类型", "帮扶日期", "参与人", "帮扶对象", "帮扶方式", "帮扶金额", "附件", "帮扶内容", "创建人", "创建时间", "编辑人", "编辑时间"};
        List<String[]> dataList = new ArrayList<>();
        for (PartyBuildingHelpRecordDto data : result) {
            String[] item = new String[headers.length];
            item[0] = data.getPartyName();
            item[1] = data.getSubject();
            item[2] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.PARTY_BUILDING_HELP_TYPE, String.valueOf(data.getType()));
            item[3] = DateUtils.format(data.getDate(), DateUtils.FormatType.SIMPLE);
            List<String> names = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(data.getBindPerson())) {
                for (PartyBuildingHelpRecordPersonBindingDto bindPerson : data.getBindPerson()) {
                    PartyPersonDto partyPersonDto = partyPersonService.selectCacheById(bindPerson.getPersonId());
                    if (partyPersonDto != null) {
                        names.add(partyPersonDto.getName());
                    }
                }
            }
            item[4] = String.join(",", names);
            item[5] = data.getHelper();
            item[6] = data.getMethod();
            item[7] = String.valueOf(data.getAmount());
            item[8] = data.getExtFiles();
            item[9] = HtmlUtils.decode(data.getRemark());
            item[10] = data.getCreator();
            item[11] = data.getCreateTime() != null ? DateUtils.format(data.getCreateTime(), DateUtils.FormatType.COMMON) : "";
            item[12] = data.getEditor();
            item[13] = data.getEditTime() != null ? DateUtils.format(data.getEditTime(), DateUtils.FormatType.COMMON) : "";
            dataList.add(item);
        }
        POIUtils.exportExcel(hresp, "党内帮扶记录", headers, dataList, "党内帮扶记录");

    }


    /**
     * 分页查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @RequirePermissions(values = "partyBuildingHelpRecord:list")
    @Operation(summary = "分页获取党内帮扶管理列表")
    public Response<Page<PartyBuildingHelpRecordDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = partyBuildingHelpRecordService.queryTotal(request.getParams());

        List<PartyBuildingHelpRecordDto> list = null;
        if (total > 0) {
            list = partyBuildingHelpRecordService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<PartyBuildingHelpRecordDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<PartyBuildingHelpRecordDto>>ok().wrap(page);
    }

    /**
     * 编辑查询反显
     *
     * @param id
     * @return
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "partyBuildingHelpRecord:edit")
    @Operation(summary = "在编辑时根据id查询党内帮扶管理详情")
    public Response<PartyBuildingHelpRecordDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (partyBuildingHelpRecordService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        PartyBuildingHelpRecordDto partyBuildingHelpRecordDto = partyBuildingHelpRecordService.selectById(id);

        return Response.<PartyBuildingHelpRecordDto>ok().wrap(partyBuildingHelpRecordDto);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "partyBuildingHelpRecord:info")
    @Operation(summary = "根据id查询党内帮扶管理的详情")
    public Response<PartyBuildingHelpRecordDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (partyBuildingHelpRecordService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        PartyBuildingHelpRecordDto partyBuildingHelpRecordDto = partyBuildingHelpRecordService.selectById(id);

        return Response.<PartyBuildingHelpRecordDto>ok().wrap(partyBuildingHelpRecordDto);
    }

    /**
     * 保存
     *
     * @param partyBuildingHelpRecordDto
     * @return
     */
    @PostMapping("save")
    @RequirePermissions(values = "partyBuildingHelpRecord:edit")
    @Operation(summary = "新增党内帮扶管理")
    public Response<Object> save(@RequestBody @Validated PartyBuildingHelpRecordDto partyBuildingHelpRecordDto) {

        //填充基础数据
        fillSaveCommonData(partyBuildingHelpRecordDto);


        partyBuildingHelpRecordDto.setPartyId(SessionHolder.getSysUser().getPartyId());

        partyBuildingHelpRecordService.saveOrUpdate(partyBuildingHelpRecordDto);

        return Response.ok();
    }


    /**
     * 修改
     *
     * @param partyBuildingHelpRecordDto
     * @return
     */
    @PostMapping("update")
    @RequirePermissions(values = "partyBuildingHelpRecord:edit")
    @Operation(summary = "根据id修改党内帮扶管理")
    public Response<Object> update(@RequestBody @Validated PartyBuildingHelpRecordDto partyBuildingHelpRecordDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(partyBuildingHelpRecordDto.getId()));
        if (partyBuildingHelpRecordService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(partyBuildingHelpRecordDto);

        partyBuildingHelpRecordService.saveOrUpdate(partyBuildingHelpRecordDto);

        return Response.ok();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("delete")
    @RequirePermissions(values = "partyBuildingHelpRecord:delete")
    @Operation(summary = "根据多条记录id批量删除党内帮扶管理")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (partyBuildingHelpRecordService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        partyBuildingHelpRecordService.deleteBatch(ids);

        return Response.ok();
    }
}
